<template>
  <div>
    <!-- 三级分类全局组件 -->
    <Category :scene="scene" />
    <!-- 属性展示 -->
    <el-card style="margin: 10px 0">
      <el-button
        type="primary"
        size="default"
        @click="handleAddAttr"
        icon="Plus"
        :disabled="!categoryStore.c3Id"
      >
        添加属性
      </el-button>
      <el-table border stripe style="margin: 10px 0" :data="attrList">
        <el-table-column
          type="index"
          width="100"
          label="序号"
        ></el-table-column>
        <el-table-column label="属性名称" width="200">
          <template #default="{ row, $index }">
            <el-input
              v-model="row.attrName"
              placeholder=""
              clearable
              @blur="handleAttrNameBlur(row)"
              :ref="(el: any) => (inputRefs[$index] = el)"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column label="属性值名称">
          <template #default="{ row, $index }">
            <el-tag
              v-for="(attr, index) in filteredAttrValueList(row.attrValueList)"
              :key="attr.id"
              closable
              @close="handleClose($index, index)"
              style="margin: 2px 5px"
            >
              {{ attr.valueName }}
            </el-tag>
            <el-input
              v-if="row.inputVisible"
              ref="InputRef"
              v-model="row.tagInput"
              class="w-20"
              size="small"
              @keyup.enter="handleInputConfirm($index)"
              @blur="handleInputConfirm($index)"
            />
            <el-button
              v-else
              class="button-new-tag"
              size="small"
              @click="showInput($index)"
            >
              + New
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ $index, row }">
            <el-popconfirm
              title="你确定要删除整行数据?"
              icon="Delete"
              icon-color="red"
              width="200"
              confirm-button-type="text"
              cancel-button-type="primary"
              @confirm="handelDeleteConfirm($index, row)"
            >
              <template #reference>
                <el-button type="danger" icon="Delete" size="small">
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- <el-button type="primary" size="default" @click="" :disabled="true">
        保存
      </el-button> -->
    </el-card>
  </div>
</template>

<script setup lang="ts">
import type { InputInstance } from 'element-plus'
// 获取分类的仓库
import useCategoryStore from '../../../store/modules/category'
// 引入监听器
import { watch, ref, nextTick, reactive, onMounted } from 'vue'
// 引入 api
import {
  reqAttrList,
  reqAddAttrValue,
  reqDeleteAttrValue,
  reqDeleteAttr,
  reqAddOrUpdateAttr,
} from '../../../api/product/attr'

// 定义属性行的类型
interface AttrRow {
  attrName: string
  originalAttrName: string
  attrValueList: { id: number; valueName: string }[]
  inputVisible: boolean
  tagInput: string
  id?: number
}

// 场景值
let scene = ref(0)

let categoryStore = useCategoryStore()
// 存储属性及属性值
let attrList = ref<AttrRow[]>([])

// 定义计算属性函数，用于过滤掉 valueName 为空的项,解决后端数据库左连接造成的数据问题
const filteredAttrValueList = (
  attrValueList: { id: number; valueName: string }[],
) => {
  return attrValueList.filter(
    (attr) => attr.valueName && attr.valueName.trim() !== '',
  )
}

// 获取属性及属性值
let getAttr = async () => {
  let result = await reqAttrList(categoryStore.c3Id)
  console.log(result)
  if (result.code === 200) {
    // 将属性列表存储到仓库中
    categoryStore.attrList = result.data.map((item) => ({
      ...item,
      originalAttrName: item.attrName,
      inputVisible: false,
      tagInput: '',
    })) as AttrRow[]
    attrList.value = categoryStore.attrList
    // console.log(attrList.value)
  }
}
// 保证在每次刷新时，组件内部的 attrList 数据重新从仓库读取，而不是丢失
onMounted(() => {
  attrList.value = categoryStore.attrList
})
// 监听三级分类的 id，当三级分类的 id 发生变化时，重新获取属性及属性值
watch(
  () => categoryStore.c3Id,
  async () => {
    if (typeof categoryStore.c3Id === 'number' && categoryStore.c3Id) {
      // 清空上一次的属性及属性值
      attrList.value = []
      // 获取属性及属性值
      await getAttr()
    }
  },
)

// el-tag
// 获取 el-tag 输入框的实例
const InputRef = ref<InputInstance>()
// 删除 tag 操作
const handleClose = (rowIndex: number, tagIndex: number) => {
  const row = attrList.value[rowIndex]
  if (row && 'attrValueList' in row) {
    // 删除属性值
    reqDeleteAttrValue(row.attrValueList[tagIndex].id)
    row.attrValueList.splice(tagIndex, 1)
  }
}

// 点击 + New Tag 展示输入框
const showInput = (rowIndex: number) => {
  attrList.value[rowIndex].tagInput = ''
  attrList.value[rowIndex].inputVisible = true
  nextTick(() => {
    InputRef.value?.input?.focus()
  })
}
// 在 Input 失去焦点或按下回车键时触发，添加 tag
const handleInputConfirm = async (rowIndex: number) => {
  const row = attrList.value[rowIndex]
  // 判断输入框是否为空
  if (row && row.tagInput) {
    row.attrValueList.push({
      valueName: row.tagInput,
      id: Date.now(), // 临时生成一个 id
    })
    let AttrValue = reactive({
      attrId: row.id,
      valueName: row.tagInput,
    })
    // 添加属性值
    await reqAddAttrValue(AttrValue)
    // console.log("添加属性值成功")
    row.inputVisible = false
  }

  // 更新页面，重新获取属性值
  getAttr()
}

// 属性名称输入框失去焦点的处理函数
const handleAttrNameBlur = (row: AttrRow) => {
  const hasValue = row.attrName.trim() !== '' || row.attrValueList.length > 0
  if (!hasValue) {
    const index = attrList.value.findIndex((item) => item === row)
    if (index !== -1) {
      attrList.value.splice(index, 1)
    }
  } else {
    if (row.attrName !== row.originalAttrName) {
      // console.log('输入内容与原内容不一致')
      // 这里可以添加更新数据的逻辑，比如发送请求更新服务器数据
      if (row.id) {
        let temp = {
          attrName: row.attrName,
          id: row.id,
          categoryId: categoryStore.c3Id,
        }
        reqAddOrUpdateAttr(temp)
      } else {
        let temp = {
          attrName: row.attrName,
          categoryId: categoryStore.c3Id,
        }
        reqAddOrUpdateAttr(temp)
      }
      row.originalAttrName = row.attrName
    } else {
      // console.log('输入内容与原内容一致')
    }
  }
}

// 用于存储每个属性名称输入框的引用
const inputRefs = ref<InputInstance[]>([])

// 属性操作，先把样式写出来，再发请求
// 添加属性按钮
const handleAddAttr = () => {
  console.log('添加属性')
  const newRow: AttrRow = {
    attrName: '',
    originalAttrName: '',
    attrValueList: [],
    inputVisible: false,
    tagInput: '',
  }
  attrList.value.push(newRow)
  nextTick(() => {
    const lastIndex = attrList.value.length - 1
    inputRefs.value[lastIndex]?.input?.focus()
  })
}
// 气泡确认框的删除操作
const handelDeleteConfirm = (rowIndex: number, row: AttrRow) => {
  console.log('删除属性')
  //请求
  if (row.id !== undefined) {
    reqDeleteAttr(row.id)
    attrList.value.splice(rowIndex, 1)
  }
}
</script>

<style scoped></style>
